<!--  -->
<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>基础信息</span>
    </div>
    <el-form :model="userForm" :rules="userFormRules" ref="userFormRef" label-width="100px">
      <el-form-item label="登录用户" prop="username">
        <el-input placeholder="请输入用户名" v-model="userForm.username" disabled></el-input>
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickname">
        <el-input placeholder="请输入用户名" v-model="userForm.nickname"></el-input>
      </el-form-item>
      <el-form-item label="用户邮箱" prop="email">
        <el-input placeholder="请输入用户邮箱" v-model="userForm.email"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitFn">提交</el-button>
        <el-button @click="resetFn">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>

</template>

<script>
import { updateUserInfoAPI } from '@/api'
export default {
  name: 'userInfo',
  data() {
    return {
      userForm: {
        username: this.$store.state.userInfo.username,
        nickname: '',
        email: '',
      },
      userFormRules: {
        nickname: [
          { required: true, message: ' 请输入昵称', trigger: 'blur' },
          { pattern:/^\S{1,10}$/,message:'昵称必须是1-10位的非空字符串',  trigger: 'blur'}
        ],
        email: [
          { required: true, message: ' 请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  methods: {
    // 提交修改的点击事件
     submitFn() { 
      this.$refs.userFormRef.validate(valid=>{
        if(valid){
          // console.log(this.userForm)

          // 因为后端在更新用户信息接口中，需要带id过去，userForm对象里本身没有id，所以需要手动添加id
          this.userForm.id=this.$store.state.userInfo.id
          updateUserInfoAPI(this.userForm).then(res=>{
            if(res.data.code===0){
              this.$message.success(res.data.message)
              // 重新让vuex获取更新后的用户信息
              this.$store.dispatch('getUserInfoActions')
            }

          })

        }else{
          this.$message.error('请输入正确的信息')
        }
      })
    },
    resetFn(){
      // this.userForm.nickname='',
      // this.userForm.email=''
      // el-form提供了一个重置表单（并且还能重置报错提示）的方法resetFields
      this.$refs.userFormRef.resetFields()
    }
}

}
</script>

<style scoped>
.el-form {
  width: 500px;
}
</style>